package com.kaiwukj.android.ufamily.mvp.ui.page.home.message;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.utils.EaseUserUtils;
import com.hyphenate.util.EasyUtils;
import com.kaiwukj.android.mcas.di.component.AppComponent;
import com.kaiwukj.android.mcas.utils.UToast;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseMvpActivity;
import com.kaiwukj.android.ufamily.app.constant.Constant;
import com.kaiwukj.android.ufamily.di.component.DaggerChatComponent;
import com.kaiwukj.android.ufamily.hx.HxEaseChatFragment;
import com.kaiwukj.android.ufamily.hx.UserCacheInfo;
import com.kaiwukj.android.ufamily.hx.UserCacheManager;
import com.kaiwukj.android.ufamily.mvp.contract.ChatContract;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.UserResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.resultbak.CommunityGroupResult;
import com.kaiwukj.android.ufamily.mvp.ui.page.home.MainActivity;

import java.util.List;
import java.util.Map;


public class ChatActivity extends BaseMvpActivity<ChatPresenter> implements ChatContract.View {
    public static ChatActivity activityInstance;
    private HxEaseChatFragment chatFragment;
    String toChatUsername;
    String toChatTitleName;


    public static void startKeeperChat(Context context, String keeperHXName) {
        if (!EMClient.getInstance().isConnected()) {
            UToast.showShort(context, "未连接到聊天服务器");
        } else if (keeperHXName.equals(EMClient.getInstance().getCurrentUser()))
            UToast.showShort(context, R.string.Cant_chat_with_yourself);
        else {
            // start chat acitivity
            // UserCacheManager.save(-1, keeperHXName, "我的管家", "");
            Intent intent = new Intent(context, ChatActivity.class);
            // it's single chat
            intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
            intent.putExtra(EaseConstant.EXTRA_USER_ID, keeperHXName);
            intent.putExtra(EaseConstant.EXTRA_USER_NAME, "我的管家");
            context.startActivity(intent);
        }
    }

    public static void startSingleChat(Context context, int userId, String hxName, String nickName, String avatarUrl) {
        if (!EMClient.getInstance().isConnected()) {
            UToast.showShort(context, "未连接到聊天服务器");
        } else if (hxName.equals(EMClient.getInstance().getCurrentUser()))
            UToast.showShort(context, R.string.Cant_chat_with_yourself);
        else {
            // start chat acitivity
            UserCacheManager.save(userId, hxName, nickName, avatarUrl);
            Intent intent = new Intent(context, ChatActivity.class);
            // it's single chat
            intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
            intent.putExtra(EaseConstant.EXTRA_USER_ID, hxName);
            intent.putExtra(EaseConstant.EXTRA_USER_NAME, nickName);
            context.startActivity(intent);
        }
    }

    public static void startSingleChat(Context context, String hxName) {
     //   LogUtils.d("json---------------------------->" + GsonUtils.toJson(EMClient.getInstance().chatManager().getConversation(hxName).getLastMessage().getStringAttribute("nickName", ":")));
        if (!EMClient.getInstance().isConnected()) {
            UToast.showShort(context, "未连接到聊天服务器");
        } else if (hxName.equals(EMClient.getInstance().getCurrentUser()))
            UToast.showShort(context, R.string.Cant_chat_with_yourself);
        else {
            // start chat acitivity
            UserCacheInfo cacheInfo = UserCacheManager.get(hxName);
            if (cacheInfo != null) {
                Intent intent = new Intent(context, ChatActivity.class);
                // it's single chat
                intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
                intent.putExtra(EaseConstant.EXTRA_USER_ID, hxName);
                intent.putExtra(EaseConstant.EXTRA_USER_NAME, cacheInfo.getNickName());
                context.startActivity(intent);
            } else {
                Intent intent = new Intent(context, ChatActivity.class);
                // it's single chat
                intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
                intent.putExtra(EaseConstant.EXTRA_USER_ID, hxName);
                intent.putExtra(EaseConstant.EXTRA_USER_NAME, EaseUserUtils.getUserInfo(hxName).getNickname());
                context.startActivity(intent);
            }
        }
    }

    /**
     * 启动单聊
     *
     * @param context    Context
     * @param userResult UserResult
     */
    public static void startSingleChat(Context context, UserResult userResult) {
        startSingleChat(context, userResult.getId(), userResult.getHxName(), userResult.getNickName(), userResult.getHeadImg());
    }

    /**
     * 启动群聊
     *
     * @param context     Context
     * @param groupHxId   群组HXID
     * @param groupName   群组名
     * @param groupAvatar 群组头像
     */
    public static void startGroupChat(Context context, int groupId, String groupHxId, String groupName, String groupAvatar) {
        if (!EMClient.getInstance().isConnected()) {
            UToast.showShort(context, "未连接到聊天服务器");
        } else {
            UserCacheManager.save(groupId, groupHxId, groupName, groupAvatar);
            Intent intent = new Intent(context, ChatActivity.class);
            intent.putExtra(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_GROUP);
            intent.putExtra(Constant.EXTRA_GROUP_TYPE, 0);
            intent.putExtra(Constant.EXTRA_USER_ID, groupHxId);
            intent.putExtra(Constant.EXTRA_USER_NAME, groupName);
            context.startActivity(intent);
        }
    }

    public static void startGroupChat(Context context, String groupHxId) {
        if (!EMClient.getInstance().isConnected()) {
            UToast.showShort(context, "未连接到聊天服务器");
        } else {
            UserCacheInfo cacheInfo = UserCacheManager.get(groupHxId);
            if (cacheInfo != null) {
                Intent intent = new Intent(context, ChatActivity.class);
                intent.putExtra(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_GROUP);
                intent.putExtra(Constant.EXTRA_GROUP_TYPE, 0);
                intent.putExtra(Constant.EXTRA_USER_ID, groupHxId);
                intent.putExtra(Constant.EXTRA_USER_NAME, cacheInfo.getNickName());
                context.startActivity(intent);
            } else {
                Intent intent = new Intent(context, ChatActivity.class);
                intent.putExtra(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_GROUP);
                intent.putExtra(Constant.EXTRA_GROUP_TYPE, 0);
                intent.putExtra(Constant.EXTRA_USER_ID, groupHxId);
                intent.putExtra(Constant.EXTRA_USER_NAME, String.format("#%s", groupHxId));
                context.startActivity(intent);
            }
        }
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerChatComponent
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_chat_message;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        if (!EMClient.getInstance().isConnected()) {
            showMessage("聊天服务器连接失败");
        }
        activityInstance = this;
        //get user id or group id
        toChatUsername = getIntent().getExtras().getString(Constant.EXTRA_USER_ID);
        toChatTitleName = getIntent().getExtras().getString(Constant.EXTRA_USER_NAME);

        Map<String, EMConversation> conversationMap = EMClient.getInstance().chatManager().getAllConversations();

 /*       subscribe(Observable.create((ObservableOnSubscribe<Boolean>) emitter -> {
            boolean hasConversation = false;
            for (EMConversation conversation : conversationMap.values()) {
                if (conversation.conversationId().equals(toChatUsername)) {
                    hasConversation = true;
                }
            }
            emitter.onNext(hasConversation);
        })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    LogUtils.d("result---------------------------------->" + result);
                    if (!result) {
                        EventBus.getDefault().postSticky(new EMClientStateEvent(EMClientStateEvent.MSG_REFRESH));
                    }
                }));*/

        //use EaseChatFratFragment
        chatFragment = new HxEaseChatFragment();
        //pass parameters to chat fragment
        chatFragment.setArguments(getIntent().getExtras());
        // chatFragment.setChatFragmentHelper(new EaseChatFragment.EaseChatFragmentHelper{});
        getSupportFragmentManager().beginTransaction().add(R.id.container, chatFragment).commit();
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        activityInstance = null;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // make sure only one chat activity is opened
        String username = intent.getStringExtra("userId");
        if (toChatUsername.equals(username))
            super.onNewIntent(intent);
        else {
            finish();
            startActivity(intent);
        }
    }

    @Override
    public void post(Runnable runnable) {

    }

    @Override
    public void onBackPressedSupport() {
        super.onBackPressedSupport();
        if (EasyUtils.isSingleActivity(this)) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
        }
    }

    public String getToChatUsername() {
        return toChatUsername;
    }

    @Override
    public Context getCtx() {
        return this;
    }

    @Override
    public void onGetNoticeList(List<CommunityGroupResult> list) {

    }

}
